
// 模拟的主页数据，开发场景使用
import { 
  recommendData, 
  hotData, 
  categoryData, 
  shareData, 
  medicineData, 
  navTabsData 
} from '../../utils/mockData.js';
// 后端请求数据
// 推荐
import {reqRecipeListData} from '../../api/index/recipeList'
// 热门
import {reqHotListData} from '../../api/index/hotList'

import { fixRecipeImagePaths } from '../../utils/imageUtils.js'

Page({

  //data数据
    data: {
    // 允许下拉刷新回弹
    isTriggered: false,
    // 导航栏数据
    currentTab: 1,
    scrollIntoView: '',
    navTabs: navTabsData,
    
    // 内容数据 - 使用占位符减少初始包大小
    recommendList: [],
    showRecommendList: [],
    hotList: [],
    showHotList: [],
    categoryList: [],
    selectedCategoryIndex: 0,
    shareList: [],
    medicineList: [],
    
    // 分页相关
    recommendPage: 1,
    hotPage: 1,
    recommendPageSize: 10,
    hotPageSize: 10,
    recommendHasMore: true,
    hotHasMore: true,
    // 分类数据
    // 家常菜
    category1:[],
    // 汤品
    category2:[],
    // 甜品
    category3:[],
    // 沙拉
    category4:[],
    // 面食
    category5:[],
    // 火锅
    category6:[],
    // 便当
    category7:[],
    // 西餐
    category8:[],

    // 上拉加载状态
    isLoadingMore: true,
    hasMore: true,
    isLoadingMoreRecommend: false,
    isLoadingMoreHot: false,

    // 搜索相关
    searchKeyword: '',
    isSearching: false,
    searchResults: [],
    showSearchResults: false,

    // 分类右侧当前展示的数据
    currentCategoryList: [],

    // 详情页数据
    
  },

  // onLoad函数
  async onLoad() {
    // 先显示加载状态
    this.setData({
      recommendList: [],
      showRecommendList: [],
      hasMore: false
    });

    // 页面加载时异步加载请求数据
    try {
      // 并行获取第一页数据
      const [recipeListData, hotListData] = await Promise.all([
        reqRecipeListData(1, this.data.recommendPageSize),
        reqHotListData()
      ]);
      // 后端请求的数据调试
      console.log("推荐数据",recipeListData.data)
      
      // 修复图片路径和解析JSON字段
      const fixedRecipeList = fixRecipeImagePaths(recipeListData.data.list || []);
      console.log("const fixedRecipeList = fixRecipeImagePaths(recipeListData.data.list || []);",fixedRecipeList)
      const fixedhHotList = fixRecipeImagePaths(hotListData.data.list || []);
      
      // 手动处理JSON字段解析问题
      fixedRecipeList.forEach(recipe => {
        if (recipe.ingredients && typeof recipe.ingredients === 'string') {
          try {
            recipe.ingredients = JSON.parse(recipe.ingredients.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            console.log('ingredients解析失败，使用默认值');
            recipe.ingredients = [
              { name: '主料', amount: '500g' },
              { name: '辅料', amount: '100g' },
              { name: '调料', amount: '适量' }
            ];
          }
        }
        if (recipe.steps && typeof recipe.steps === 'string') {
          try {
            recipe.steps = JSON.parse(recipe.steps.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            console.log('steps解析失败，使用默认值');
            recipe.steps = [];
          }
        }
        if (recipe.nutrition && typeof recipe.nutrition === 'string') {
          try {
            recipe.nutrition = JSON.parse(recipe.nutrition.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            console.log('nutrition解析失败，使用默认值');
            recipe.nutrition = {};
          }
        }
      });

      // 设置推荐数据
      this.setData({
        recommendList: fixedRecipeList,
        showRecommendList: fixedRecipeList,
        recommendHasMore: fixedRecipeList.length >= this.data.recommendPageSize,
        
        hotList: fixedhHotList,
        showHotList: fixedhHotList,
        hotHasMore: fixedhHotList.length >= this.data.hotPageSize,
        // 家常菜
        category1:fixedRecipeList,
        // 汤品
        category2:fixedhHotList,
        // 甜品
        category3:fixedRecipeList,
        // 沙拉
        category4:fixedhHotList,
        // 面食
        category5:fixedRecipeList,
        // 火锅
        category6:fixedhHotList,
        // 便当
        category7:fixedRecipeList,
        // 西餐
        category8:fixedhHotList,
        currentCategoryList: fixedRecipeList
      });
      console.log("recommendHasMore: fixedRecipeList.length >= this.data.recommendPageSize,",fixedRecipeList.length)
    } catch (error) {
      console.error('数据加载失败:', error);
      // 使用模拟数据作为备用
      this.setData({
        recommendList: recommendData,
        showRecommendList: recommendData.slice(0, 6),
        recommendHasMore: recommendData.length > 6,
        hotList: hotData,
        showHotList: hotData.slice(0, 6),
        hotHasMore: hotData.length > 6
      });
    }
    
    // 立即加载其他页面数据，不使用延迟
    this.setData({
      categoryList: categoryData,
      shareList: shareData,
      medicineList: medicineData
    }, () => {
      this.buildRightCategoryItems(0);
    });
    console.log('所有页面数据加载完成');
  },

    // onShow
    onShow() {
      // 主页导航栏默认设置 selected：0代表默认为推荐
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          selected: 0
        });
      }
      
    },

  // 模拟主页列表数据
  // 异步加载页面数据
  loadPageData() {
    // 模拟异步加载数据
    return new Promise((resolve) => {
      setTimeout(() => {
        
        this.setData({
          categoryList: categoryData,
          shareList: shareData,
          medicineList: medicineData
        }, () => {
          resolve();
        });
      }, 100);
    });
  },


  // 标签点击事件
  onTabClick(e) {
    const index = e.currentTarget.dataset.index;
    
    this.setData({
      currentTab: index,
      scrollIntoView: `nav-${index}`
    });
    
    // 如果切换到需要数据的标签页，确保数据已加载
    if (index >= 2) {
      const needsData = this.data.categoryList.length === 0 || 
                       this.data.shareList.length === 0 || 
                       this.data.medicineList.length === 0;
      
      if (needsData) {
        // 立即加载数据，不使用延迟
        this.setData({
          categoryList: categoryData,
          shareList: shareData,
          medicineList: medicineData
        });
      }
      
      // 如果是分类标签，初始化分类状态
      if (index === 2) {
        this.setData({
          selectedCategoryIndex: 0,
          rightCategoryItems: []
        });
        // 延迟一点时间确保数据已设置，然后构建右侧内容
        setTimeout(() => {
          this.buildRightCategoryItems(0);
        }, 50);
      }
    }
  },

  // 分类：左侧点击
  onCategorySelect(e) {
    const index = Number(e.currentTarget.dataset.index || 0);
    if (index === this.data.selectedCategoryIndex) return;
    this.setData({ selectedCategoryIndex: index });
    // 将点击的类别映射到对应的数组
    const mapping = [
      this.data.category1,
      this.data.category2,
      this.data.category3,
      this.data.category4,
      this.data.category5,
      this.data.category6,
      this.data.category7,
      this.data.category8
    ];
    const list = mapping[index] || [];
    this.setData({ currentCategoryList: list });
  },

  // 搜索输入事件
  onSearchInput(e) {
    const keyword = e.detail.value.trim();
    this.setData({ searchKeyword: keyword });
    
    if (keyword.length > 0) {
      this.performSearch(keyword);
    } else {
      this.setData({ 
        showSearchResults: false,
        searchResults: []
      });
    }
  },

  // 搜索框聚焦事件
  onSearchFocus() {
    this.setData({ isSearching: true });
  },

  // 搜索框失焦事件
  onSearchBlur() {
    // 延迟隐藏搜索结果，让用户有时间点击结果
    setTimeout(() => {
      this.setData({ isSearching: false });
    }, 200);
  },

  // 执行搜索
  performSearch(keyword) {
    if (!keyword) {
      this.setData({ 
        showSearchResults: false,
        searchResults: []
      });
      return;
    }

    // 在所有数据中搜索
    const allData = [
      ...this.data.recommendList,
      ...this.data.hotList,
      ...this.data.shareList,
      ...this.data.medicineList
    ];

    const results = allData.filter(item => {
      const name = item.meishiName || item.title || '';
      const content = item.meishiContent || item.description || '';
      return name.toLowerCase().includes(keyword.toLowerCase()) || 
             content.toLowerCase().includes(keyword.toLowerCase());
    });

    this.setData({
      searchResults: results,
      showSearchResults: true
    });
  },

  // 清除搜索
  onClearSearch() {
    this.setData({
      searchKeyword: '',
      searchResults: [],
      showSearchResults: false
    });
  },

  // 搜索项点击
  onSearchItemTap(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.searchResults[index];
    
    // 跳转到详情页
    wx.navigateTo({
      url: `/pages/index/detail/detail?id=${item.id}&type=search`
    });
  },

  // 构建右侧内容（示例：以所选分类名生成占位内容）
  buildRightCategoryItems(index) {
    const category = this.data.categoryList[index];
    if (!category) {
      this.setData({ rightCategoryItems: [] });
      return;
    }
    // 这里用简单占位数据，真实项目可请求接口按分类拉取
    const items = Array.from({ length: 8 }).map((_, i) => ({
      title: `${category.name} · 推荐${i + 1}`,
      icon: category.icon
    }));
    this.setData({ rightCategoryItems: items });
  },

  // 图片加载失败处理
  onImageError(e) {
    const index = e.currentTarget.dataset.index;
    const type = e.currentTarget.dataset.type;
    console.log('图片加载失败:', index, type);
    
    // 设置默认图片
    const defaultImage = '/assets/images/recipe1.jpg';
    const dataKey = type === 'recommend' ? 'showRecommendList' : 'recommendList';
    
    this.setData({
      [`${dataKey}[${index}].meishiPhoto`]: defaultImage
    });
  },

  // 自定义上拉加载
  async getMore() {
    // 仅在"推荐" "热门"页生效
    if (this.data.currentTab !== 0 && this.data.currentTab !== 1) return;
    
    if (this.data.currentTab === 0) {
      // 热门页
      await this.loadMoreHot();
    } else if (this.data.currentTab === 1) {
      // 推荐页
      await this.loadMoreRecommend();
    }
  },

  // 加载更多推荐数据
  async loadMoreRecommend() {
    if (this.data.isLoadingMoreRecommend || !this.data.recommendHasMore) {
      if (!this.data.recommendHasMore) {
        wx.showToast({ title: '没有更多了', icon: 'none' });
      }
      return;
    }

    this.setData({ isLoadingMoreRecommend: true });
    wx.showLoading({ title: '加载中...' });

    try {
      const nextPage = this.data.recommendPage + 1;
      console.log("const nextPage = this.data.recommendPage + 1;",nextPage)
      const recipeListData = await reqRecipeListData(nextPage, this.data.recommendPageSize);
      console.log("const recipeListData = await reqRecipeListData(nextPage, this.data.recommendPageSize);",recipeListData)
      const newData = fixRecipeImagePaths(recipeListData.data.list || []);
      
      // 处理JSON字段
      newData.forEach(recipe => {
        if (recipe.ingredients && typeof recipe.ingredients === 'string') {
          try {
            recipe.ingredients = JSON.parse(recipe.ingredients.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            recipe.ingredients = [
              { name: '主料', amount: '500g' },
              { name: '辅料', amount: '100g' },
              { name: '调料', amount: '适量' }
            ];
          }
        }
        if (recipe.steps && typeof recipe.steps === 'string') {
          try {
            recipe.steps = JSON.parse(recipe.steps.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            recipe.steps = [];
          }
        }
        if (recipe.nutrition && typeof recipe.nutrition === 'string') {
          try {
            recipe.nutrition = JSON.parse(recipe.nutrition.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            recipe.nutrition = {};
          }
        }
      });

      const hasMore = newData.length >= this.data.recommendPageSize;
      
      this.setData({
        recommendList: [...this.data.recommendList, ...newData],
        showRecommendList: [...this.data.showRecommendList, ...newData],
        recommendPage: nextPage,
        recommendHasMore: hasMore,
        isLoadingMoreRecommend: false
      });

      wx.hideLoading();
      if (!hasMore) {
        wx.showToast({ title: '已加载全部', icon: 'none' });
      }
    } catch (error) {
      console.error('加载更多推荐失败:', error);
      wx.hideLoading();
      wx.showToast({ title: '加载失败', icon: 'none' });
      this.setData({ isLoadingMoreRecommend: false });
    }
  },

  // 加载更多热门数据
  async loadMoreHot() {
    if (this.data.isLoadingMoreHot || !this.data.hotHasMore) {
      if (!this.data.hotHasMore) {
        wx.showToast({ title: '没有更多了', icon: 'none' });
      }
      return;
    }

    this.setData({ isLoadingMoreHot: true });
    wx.showLoading({ title: '加载中...' });

    try {
      // 热门数据暂时使用模拟数据，实际项目中应该有对应的分页接口
      const newData = hotData.slice(this.data.showHotList.length, this.data.showHotList.length + this.data.hotPageSize);
      const hasMore = newData.length >= this.data.hotPageSize;
      
      this.setData({
        hotList: [...this.data.hotList, ...newData],
        showHotList: [...this.data.showHotList, ...newData],
        hotPage: this.data.hotPage + 1,
        hotHasMore: hasMore,
        isLoadingMoreHot: false
      });

      wx.hideLoading();
      if (!hasMore) {
        wx.showToast({ title: '已加载全部', icon: 'none' });
      }
    } catch (error) {
      console.error('加载更多热门失败:', error);
      wx.hideLoading();
      wx.showToast({ title: '加载失败', icon: 'none' });
      this.setData({ isLoadingMoreHot: false });
    }
  },

  // 自定义下拉刷新
  async refreshHandler() {
    try {
      // 重置分页状态
      this.setData({
        recommendPage: 1,
        hotPage: 1,
        recommendHasMore: true,
        hotHasMore: true
      });

      // 重新获取第一页数据
      const [recipeListData, hotListData] = await Promise.all([
        reqRecipeListData(1, this.data.recommendPageSize),
        reqHotListData()
      ]);
      
      const fixedRecipeList = fixRecipeImagePaths(recipeListData.data.list || []);
      const fixedHotList = fixRecipeImagePaths(hotListData.data.list || []);
      
      // 手动处理JSON字段解析问题
      fixedRecipeList.forEach(recipe => {
        if (recipe.ingredients && typeof recipe.ingredients === 'string') {
          try {
            recipe.ingredients = JSON.parse(recipe.ingredients.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            recipe.ingredients = [
              { name: '主料', amount: '500g' },
              { name: '辅料', amount: '100g' },
              { name: '调料', amount: '适量' }
            ];
          }
        }
        if (recipe.steps && typeof recipe.steps === 'string') {
          try {
            recipe.steps = JSON.parse(recipe.steps.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            recipe.steps = [];
          }
        }
        if (recipe.nutrition && typeof recipe.nutrition === 'string') {
          try {
            recipe.nutrition = JSON.parse(recipe.nutrition.replace(/[\r\n\t]/g, '').replace(/\s+/g, ' ').trim());
          } catch (e) {
            recipe.nutrition = {};
          }
        }
      });
      
      this.setData({
        recommendList: fixedRecipeList,
        showRecommendList: fixedRecipeList,
        recommendHasMore: fixedRecipeList.length >= this.data.recommendPageSize,
        hotList: fixedHotList,
        showHotList: fixedHotList,
        hotHasMore: fixedHotList.length >= this.data.hotPageSize,
        // 重置分类状态
        selectedCategoryIndex: 0,
        rightCategoryItems: [],
        isTriggered: false
      });
      
      // 重新加载分类数据并初始化右侧内容
      this.loadPageData().then(() => {
        this.buildRightCategoryItems(0);
      });
      
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('刷新失败:', error);
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      });
      this.setData({
        isTriggered: false
      });
    }
  },

  // 点击食谱缩览图进入详情页
  onDetail(event) {
    // 从 data-* 读取索引与类型
    const index = Number(event.currentTarget.dataset.index);
    const type = event.currentTarget.dataset.type || 'recommend';
    // 

    // 根据类型选择数据源
    const sourceMap = {
      recommend: this.data.recommendList,
      hot: this.data.hotList,
      share: this.data.shareList,
      medicine: this.data.medicineList
    };
    const list = sourceMap[type] || this.data.recommendList;
    const item = Array.isArray(list) ? list[index] : null;
    console.log('list',list)

    // 跳转并通过两种方式传参：
    // 1) URL 参数兜底（index/type）
    // 2) eventChannel 直接传对象，避免详情页再次查找
    wx.navigateTo({
      url: `/pages/index/detail/detail?index=${index}&type=${type}`,
      success: (res) => {
        if (item) {
          res.eventChannel.emit('recipeData', { item, type, index });
        }
      }
    });
  },

  // 主页跳转通知页面
  onNotice() {
    wx.navigateTo({
      url: '/pages/notice/notice',
    })
  }
  })
  